/*
 * Copyright 2006 George Georgovassilis <g.georgovassilis[at]gmail.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.javaongems.user.gwthandler;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import org.gwtwidgets.server.spring.GWTHandler;
import org.gwtwidgets.server.spring.GWTSpringController;

import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.SerializableException;


/**
 * Callback for CGLIB which determines wether the method invoked belongs to the
 * delegate object or the CGLIB-enhanced {@link GWTSpringController}. This
 * class is for internal use of the {@link GWTHandler}.
 * 
 * notes: - simplified & short circuited lookup 
 * @author Ashin Wimalajeewa (ash)
 * 
 */
public class CgLibCallback implements MethodInterceptor {
	private RemoteService target;
	private boolean unwrapExceptions;
	
	private Method setThreadLocalHttpServletRequestMethod;
	private Class targetClass;
	private Map/*<Method, Method>*/ callInterfaceMethods = new HashMap/*<Method, Method>*/();

	/**
	 * Wrap this callback around a service
	 * 
	 * @param target
	 * @param true
	 *            if you want {@link SerializableException} instances to be
	 *            unwrapped
	 */
	public CgLibCallback(RemoteService target, boolean unwrapExceptions) {
		this.target = target;
		this.unwrapExceptions = unwrapExceptions;
		prepareCallInterface();
	}

	public Object intercept(Object obj, Method method, Object[] args,
			MethodProxy proxy) throws Throwable {
		boolean isAbs = Modifier.isAbstract(method.getModifiers());
		if (!isAbs)
			return proxy.invokeSuper(obj, args);
		try {
			return invokeCallInterfaceMethod(method, args);
		} catch (Throwable e) {
			if (!unwrapExceptions) throw e;
			Throwable cause = e;
			while (true){
				if (cause == null) throw e;
				if (cause instanceof SerializableException) throw cause;
				cause = cause.getCause();
			}
		}
	}
	
	private Object invokeCallInterfaceMethod(Method method, Object[] args) throws Throwable {
		Method invoker = (Method) callInterfaceMethods.get(method);
		if (setThreadLocalHttpServletRequestMethod != null) {
			Object[] raArgs = new Object[] {GWTSpringController.getRequest()};
			setThreadLocalHttpServletRequestMethod.invoke(target, raArgs);
		}
		if (invoker == null) {
			invoker = targetClass.getMethod(method.getName(), method.getParameterTypes());
			callInterfaceMethods.put(method, invoker);
		}
		return invoker.invoke(target, args);
	}
	
	private void prepareCallInterface() {
		targetClass = target.getClass();
		setThreadLocalHttpServletRequestMethod = Utils.querySetThreadLocalHttpServletRequestMethod(targetClass);
	}
}
